import 'dart:async';

import 'package:fish_redux/fish_redux.dart';

import 'action.dart';
import 'state.dart';

Effect<MyHomeState> buildEffect() {
  return combineEffects(<Object, Effect<MyHomeState>>{
    MyHomeAction.action: _onAction,
    Lifecycle.didChangeDependencies: _didChangeDependencies,
    Lifecycle.initState: _initState,
  });
}

void _onAction(Action action, Context<MyHomeState> ctx) {
  print('effect on action');
}

void _didChangeDependencies(Action action, Context<MyHomeState> ctx) {
  ctx.dispatch(MyHomeActionCreator.onWindowSizeChange());
}

void _initState(Action action, Context<MyHomeState> ctx) {
  var timer = Timer.periodic(Duration(milliseconds: 80), (timer) {
    // ignore: invalid_use_of_protected_member
    if (ctx.state.controller.positions.isNotEmpty) {
      ctx.state.controller.animateTo(ctx.state.controller.offset + 1);
    }
  });

  ctx.state.controller.addListener(() {
    print(ctx.state.controller.offset); //打印滚动位置
    if (ctx.state.controller.offset >= 300) {
      timer.cancel();
      ctx.state.controller.jumpTo(.0);
      timer = Timer.periodic(Duration(milliseconds: 80), (timer) {
        // ignore: invalid_use_of_protected_member
        if (ctx.state.controller.positions.isNotEmpty) {
          ctx.state.controller.animateTo(ctx.state.controller.offset + 1);
        }
      });
    }
  });
}
